package session

import (
	"context"
	db "cybertwin/db/sqlc"
	"cybertwin/utils/configtools"
	"database/sql"
	"fmt"

	_ "github.com/lib/pq"
	log "github.com/sirupsen/logrus"
)

var (
	dbDriver = "postgres"
	dbSource = "postgresql://root:secret@localhost:5432/cybertwin?sslmode=disable"
)

var cybertwinDB *sql.DB

func init() {
	var err error
	if checkDBConfigEmptyValid() {
		dbSource = configtools.DatabaseConfiguration.GetString("dbSource")
		dbDriver = configtools.DatabaseConfiguration.GetString("dbDriver")
		log.WithFields(log.Fields{
			"dbSource": dbSource,
			"dbDriver": dbDriver,
		}).Infof("[dbconn.go]-[init]-使用/config/pgconfig.yaml配置项")
		cybertwinDB, err = sql.Open(dbDriver, dbSource)
		if err != nil {
			log.Fatalln("[dbconn.go]-[init]-无法连接至数据库，检查dbDriver和dbSource常量的设置: error=" + err.Error())
			return
		}
		log.Infoln("[dbcoon.go]-[init]-成功连接至cybertwin数据库")
	} else {
		log.Infoln("[dbconn.go]-[init]-无法找到/config/pgconfig.yaml，使用默认的数据库连接配置")
		cybertwinDB, err = sql.Open(dbDriver, dbSource)
		if err != nil {
			log.Fatalln("[dbconn.go]-[init]-无法连接至数据库，检查dbDriver和dbSource常量的设置: error=" + err.Error())
			return
		}
		log.Infoln("[dbcoon.go]-[init]-成功连接至cybertwin数据库")
	}
}

type DBTXQuery struct {
	*db.Queries
	db *sql.DB
}

func NewDBTXQuery() *DBTXQuery {
	return &DBTXQuery{
		db:      cybertwinDB, // 用于创建事务的，创建事务不能直接用Query
		Queries: db.New(cybertwinDB),
	}
}

func (txQuery *DBTXQuery) execTx(ctx context.Context, fn func(queries *db.Queries) error) error {
	tx, err := txQuery.db.BeginTx(ctx, nil)

	if err != nil {
		return err
	}

	q := db.New(tx)
	err = fn(q)
	if err != nil {
		if rollbackErr := tx.Rollback(); rollbackErr != nil {
			return fmt.Errorf("tx error: %v, rollback err = %v", err, rollbackErr)
		}
		return err
	}
	return tx.Commit()
}

type UeRegisterTXParam struct {
	InsertRegisteredUeParam db.InsertRegisteredUeParams
	Uid                     string
}

func NewDBQuery() *db.Queries {
	return db.New(cybertwinDB)
}
